<script setup>
import { ref } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'  // 添加ElMessage导入
import { reqeust } from '@/api/request'

const fileList = ref([])
const dialogVisible = ref(false)
const disabled = ref(false)

const handleChange = (file, files) => {
  fileList.value = files
}

const handleRemove = (file) => {
  fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
}

const handlePreview = (file) => {
  // 对于音乐文件，可能无法预览，可以显示一些信息或者不做任何操作
  ElMessage.info('音乐文件无法预览')
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传一个音乐文件')
}

const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择音乐文件后再上传')
    return
  }

  const formData = new FormData()
  formData.append('file', fileList.value[0].raw)

  const response = await reqeust({
    url:'/song/upload-song',  // 这里可能需要修改为音乐上传的API路径
    method: 'POST',
    data:formData, 
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })

  ElMessage.success('上传成功')
  console.log('上传结果:', response.data)
  // 这里可以触发父组件的事件或处理上传成功后的逻辑
  emit('upload-success', response.data)
}

// 定义emit
const emit = defineEmits(['upload-success'])
</script>

<template>
  <div class="music-upload-container">
    <el-upload 
      class="upload-demo" 
      action="" 
      :auto-upload="false" 
      :on-change="handleChange" 
      :file-list="fileList"
      :limit="1" 
      :on-exceed="handleExceed"
      accept="audio/*">  <!-- 只接受音频文件 -->
      
      <template #trigger>
        <el-button type="primary">选择音频文件</el-button>
      </template>
      &nbsp;<el-button type="primary" @click="submitUpload">上传音乐</el-button>
      <template #tip>
        <div class="el-upload__tip text-red">
          只能上传一个音频文件, 新文件覆盖前一个文件
        </div>
      </template>
      <!-- <template #file="{ file }">
        <div class="music-file-item">
          <el-icon><Plus /></el-icon>
          <span class="music-file-name">{{ file.name }}</span>
          <span v-if="!disabled" class="music-file-delete" @click="handleRemove(file)">
            <el-icon><Delete /></el-icon>
          </span>
        </div>
      </template> -->
    </el-upload>

    <!-- 音乐文件不需要预览对话框 -->
    
  </div>
</template>

<style scoped>
.music-upload-container {
  margin: 20px;
}

.music-file-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.music-file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.music-file-delete {
  cursor: pointer;
  color: #f56c6c;
}
</style>